package com.project.friend.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.project.common.core.domain.TableDataInfo;
import com.project.friend.domain.question.Question;
import com.project.friend.domain.question.dto.QuestionQueryDTO;
import com.project.friend.domain.question.es.QuestionES;
import com.project.friend.domain.question.vo.QuestionDetailVO;
import com.project.friend.elasticserch.QuestionRepository;
import com.project.friend.manager.QuestionCacheManager;
import com.project.friend.mapper.question.QuestionMapper;
import com.project.friend.service.question.IQuestionService;
import com.project.system.domain.question.vo.QuestionVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class QuestionServiceImpl implements IQuestionService {
    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private QuestionCacheManager questionCacheManager;

    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        //es中获取题目数量
        long count = questionRepository.count();
        if(count <= 0){
            //如果没查出数据 则说明es中没用存储 刷新数据es中
            refreshQuestion();
        }
        //根据创建时间降序排序
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //分页参数
        Pageable pageable = PageRequest.of(questionQueryDTO.getPageNum() - 1, questionQueryDTO.getPageSize(), sort);
        //获取难度和关键词参数
        Integer difficulty = questionQueryDTO.getDifficulty();
        String keyword = questionQueryDTO.getKeyword();
        Page<QuestionES> questionESPage;
        //判断是否获取到了难度和关键词参数
        if(difficulty == null && StrUtil.isEmpty(keyword)){
            //两个都没有 全部获取
            questionESPage = questionRepository.findAll(pageable);
        }else if(StrUtil.isEmpty(keyword)){
            //g关键词为空 根据难度查询
            questionESPage = questionRepository.findQuestionByDifficulty(difficulty,pageable);
        }else if(difficulty == null){
            //难度为空
            questionESPage = questionRepository.findByTitleOrContent(keyword,keyword,pageable);
        }else {
            //都不为空
            questionESPage = questionRepository.findByTitleOrContentAndDifficulty(keyword,keyword,difficulty,pageable);
        }
        //获取总数
        long total = questionESPage.getTotalElements();
        if(total <= 0){
            return TableDataInfo.empty();
        }
        List<QuestionES> questionESList = questionESPage.getContent();
        //将es列表转化为返回值需要的列表
        List<QuestionVO> questionVOList = BeanUtil.copyToList(questionESList, QuestionVO.class);

        return TableDataInfo.success(questionVOList,total);
    }

    /**
     * 查询题目详情 先es 在数据库
     * @param questionId
     * @return
     */
    @Override
    public QuestionDetailVO detail(Long questionId) {
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        if (questionES != null) {
            //在es中找到了数据 直接返回
            BeanUtil.copyProperties(questionES, questionDetailVO);
            return questionDetailVO;
        }
        //如果没找到就差数据库
        Question question = questionMapper.selectById(questionId);
        if (question == null) {
            return null;
        }
        refreshQuestion();
        BeanUtil.copyProperties(question, questionDetailVO);
        //将数据库中的数据同步到es
        return questionDetailVO;
    }

    @Override
    public String preQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.preQuestion(questionId).toString();
    }

    @Override
    public String nextQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.nextQuestion(questionId).toString();
    }

    private void refreshQuestion() {
        //数据库中获取题目列表
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>());
        if (CollectionUtil.isEmpty(questionList)){
            return;
        }
        List<QuestionES> questionESList = BeanUtil.copyToList(questionList, QuestionES.class);
        //转化为es列表后全部存储到es中
        questionRepository.saveAll(questionESList);
    }
}
